use std::sync::mpsc;
use std::thread;
use std::thread::JoinHandle;
use std::time::Duration;

fn ths() -> JoinHandle<()> {
    return thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });
}

fn th_with_closure() {
    let v = vec![1, 2, 3];

    // 不能运行，借用了v，但生命周期不确定。
    /*
    let handle = thread::spawn( || {
        println!("Here is a vector: {:?}", v);
    });
    */
    let handle = thread::spawn(move || {
        println!("Here is a vector: {:?}", v);
    });
    handle.join().unwrap();

    // 已move不能使用了。
    // println!("vector: {:?}", v);
}

fn ch() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let v = String::from("hello");
        tx.send(v).unwrap();
    });

    let r = rx.recv().unwrap();
    println!("Got: {}", r);
}

fn main() {
    println!("Hello, world!");
    let h = ths();
    // 一旦主线程退出，子线程可能不能正常结束。
    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
    th_with_closure();

    // join等待线程退出。
    h.join().unwrap();
    ch();
}
